/**
 * 用于监听文件变化执行热更新
 * 
 */

import chokidar from 'chokidar';
import path from 'path';
import { JsonAstCode, CodeAstJson } from "./index.js";

// 将修改文件到热更新文件列为一个事务，事务结束，热更新流程结束
let transaction = 'begin';

let doTransaction = () => {
    transaction = transaction === 'begin' ? 'end' : 'begin';
}

export default class Watch {
    constructor(config) {
        this.config = config;
        this.setup();
    }

    setup = () => {
        this.watchJson();
        // this.watchCode();
    }

    watchJson = () => {
        const { jsonDir } = this.config;
        chokidar.watch(jsonDir).on('change', (path) => {
            console.log('热更新文件', path);
            // if (transaction === 'begin') {
                this.jsonAstCode(`./${path}`, () => {
                    // doTransaction();
                })
            // } else {
            //     doTransaction();
            // }
        });
    }

    watchCode = () => {
        const { codeDir } = this.config;
        chokidar.watch(codeDir).on('change', (path) => {
            console.log('热更新文件', path);
            if (transaction === 'begin') {
                this.codeAstJson(`./${path}`, () => {
                    doTransaction();
                })
            } else {
                doTransaction();
            }
        });
    }

    jsonAstCode = (filePath, finishedCallback) => {
        const { jsonDir, codeDir, ...projectConfig } = this.config;
        const entryPath = path.join(process.cwd(), filePath);
        const outputPath = path.join(
            process.cwd(), filePath.replace(new RegExp(`^${jsonDir}`), codeDir)
                .replace(new RegExp('js$'), 'jsx'))

        new JsonAstCode({
            entryPath,
            outputPath,
            projectConfig,
            finishedCallback
        })
    }

    codeAstJson = (filePath, finishedCallback) => {
        const { jsonDir, codeDir, ...projectConfig } = this.config;
        const entryPath = path.join(process.cwd(), filePath);
        const outputPath = path.join(process.cwd(), filePath.replace(new RegExp(`^${codeDir}`), jsonDir)
            .replace(new RegExp('jsx$'), 'js'))

        new CodeAstJson({
            entryPath,
            outputPath,
            projectConfig,
            finishedCallback
        })
    }
}